<!DOCTYPE html>
<html>

<head>
  <title>Quarkus - GraphQL</title>
  <script id="adobe_dtm" src="https://www.redhat.com/dtm.js" type="text/javascript"></script>
  <script src="/assets/javascript/highlight.pack.js" type="text/javascript"></script>
  <META HTTP-EQUIV='Content-Security-Policy' CONTENT="default-src 'none'; script-src 'self' 'unsafe-eval' 'sha256-ANpuoVzuSex6VhqpYgsG25OHWVA1I+F6aGU04LoI+5s=' 'sha256-ipy9P/3rZZW06mTLAR0EnXvxSNcnfSDPLDuh3kzbB1w=' js.bizographics.com https://www.redhat.com assets.adobedtm.com jsonip.com https://ajax.googleapis.com https://www.googletagmanager.com https://www.google-analytics.com https://use.fontawesome.com; style-src 'self' https://fonts.googleapis.com https://use.fontawesome.com; img-src 'self' *; media-src 'self' ; frame-src https://www.googletagmanager.com https://www.youtube.com; frame-ancestors 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; font-src 'self' https://use.fontawesome.com https://fonts.gstatic.com;">
  <META HTTP-EQUIV='X-Frame-Options' CONTENT="DENY">
  <META HTTP-EQUIV='X-XSS-Protection' CONTENT="1; mode=block">
  <META HTTP-EQUIV='X-Content-Type-Options' CONTENT="nosniff">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Quarkus: Supersonic Subatomic Java">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:site" content="@QuarkusIO"> 
  <meta name="twitter:creator" content="@QuarkusIO">
  <meta property="og:url" content="https://quarkus.io/guides/microprofile-graphql" />
  <meta property="og:title" content="Quarkus - GraphQL" />
  <meta property="og:description" content="Quarkus: Supersonic Subatomic Java" />
  <meta property="og:image" content="/assets/images/quarkus_card.png" />
  <link rel="canonical" href="https://quarkus.io/guides/microprofile-graphql">
  <link rel="shortcut icon" type="image/png" href="/favicon.ico" >
  <link rel="stylesheet" href="https://quarkus.io/guides/stylesheet/config.css" />
  <link rel="stylesheet" href="/assets/css/main.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
  <link rel="alternate" type="application/rss+xml"  href="https://quarkus.io/feed.xml" title="Quarkus">
  <script src="https://quarkus.io/assets/javascript/goan.js" type="text/javascript"></script>
  <script src="https://quarkus.io/assets/javascript/hl.js" type="text/javascript"></script>
</head>

<body class="guides">
  <!-- Google Tag Manager (noscript) -->
  <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-NJWS5L"
  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
  <!-- End Google Tag Manager (noscript) -->

  <div class="nav-wrapper">
  <div class="grid-wrapper">
    <div class="width-12-12">
      <input type="checkbox" id="checkbox" />
      <nav id="main-nav" class="main-nav">
  <div class="container">
    <div class="logo-wrapper">
      
        <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_600px_reverse.png" class="project-logo" title="Quarkus"></a>
      
    </div>
    <label class="nav-toggle" for="checkbox">
      <i class="fa fa-bars"></i>
    </label>
    <div id="menu" class="menu">
      <span>
        <a href="/get-started/" class="">Get Started</a>
      </span>
      <span>
        <a href="/guides/" class="active">Guides</a>
      </span>
      <span>
        <a href="/community/" class="">Community</a>
      </span>
      <span>
        <a href="/support/" class="">Support</a>
      </span>
      <span>
        <a href="/blog/" class="">Blog</a>
      </span>
      <span>
        <a href="https://code.quarkus.io" class="button-cta secondary white">Start Coding</a>
      </span>
    </div>
  </div>
      </nav>
    </div>
  </div>
</div>

  <div class="content">
    <div class="guide">
  <div class="width-12-12">
    <h1 class="text-caps">Quarkus - GraphQL</h1>
    <div class="hide-mobile toc"><ul class="sectlevel1">
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#architecture">Architecture</a></li>
<li><a href="#solution">Solution</a></li>
<li><a href="#creating-the-maven-project">Creating the Maven Project</a></li>
<li><a href="#preparing-an-application-graphql-api">Preparing an Application: GraphQL API</a></li>
<li><a href="#launch">Launch</a></li>
<li><a href="#introspect">Introspect</a></li>
<li><a href="#graphiql-ui">GraphiQL UI</a></li>
<li><a href="#query-the-graphql-api">Query the GraphQL API</a></li>
<li><a href="#expanding-the-api">Expanding the API</a></li>
<li><a href="#mutations">Mutations</a></li>
<li><a href="#creating-queries-by-fields">Creating Queries by fields</a></li>
<li><a href="#context">Context</a>
<ul class="sectlevel2">
<li><a href="#graphql-java">GraphQL-Java</a></li>
</ul>
</li>
<li><a href="#map-to-scalar">Map to Scalar</a>
<ul class="sectlevel2">
<li><a href="#mapping-an-existing-scalar-to-another-type">Mapping an existing Scalar to another type:</a></li>
<li><a href="#mapping-a-complex-object-to-a-scalar-type">Mapping a complex object to a Scalar type:</a></li>
</ul>
</li>
<li><a href="#error-code">Error code</a></li>
<li><a href="#conclusion">Conclusion</a></li>
<li><a href="#configuration-reference">Configuration Reference</a></li>
</ul></div>
    <div>
      <div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>This guide demonstrates how your Quarkus application can utilize the <strong>Eclipse MicroProfile
GraphQL</strong> specification through the SmallRye GraphQL extension.</p>
</div>
<div class="paragraph">
<p>As the <a href="https://www.graphql.org/">GraphQL</a> specification website states:</p>
</div>
<div class="quoteblock">
<blockquote>
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.
GraphQL provides a complete and understandable description of the data in your API,
gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time,
and enables powerful developer tools.
</blockquote>
</div>
<div class="paragraph">
<p><strong>GraphQL</strong> was originally developed by <strong>Facebook</strong> in 2012 and has been
an open standard since 2015.</p>
</div>
<div class="paragraph">
<p>GraphQL is not a replacement for REST API specification but merely an
alternative. Unlike REST, GraphQL API&#8217;s have the ability to benefit the client by:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Preventing Over-fetching and Under-fetching</dt>
<dd>
<p>REST API&#8217;s are server-driven fixed data responses that cannot be determined by
the client. Although the client does not require all the fields the client
must retrieve all the data hence <code>Over-fetching</code>. A client may also require
multiple REST API calls according to the first call (HATEOAS) to retrieve
all the data that is required thereby <code>Under-fetching</code>.</p>
</dd>
<dt class="hdlist1">API Evolution</dt>
<dd>
<p>Since GraphQL API&#8217;s returns data that are requested by the client adding additional
fields and capabilities to existing API will not create breaking changes to existing
clients.</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="sect1">
<h2 id="prerequisites"><a class="anchor" href="#prerequisites"></a>Prerequisites</h2>
<div class="sectionbody">
<div class="paragraph">
<p>To complete this guide, you need:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>less than 15 minutes</p>
</li>
<li>
<p>an IDE</p>
</li>
<li>
<p>JDK 1.8+ installed with <code>JAVA_HOME</code> configured appropriately</p>
</li>
<li>
<p>Apache Maven 3.6.2+</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="architecture"><a class="anchor" href="#architecture"></a>Architecture</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In this guide, we build a simple GraphQL application that exposes a GraphQL API
at <code>/graphql</code>.</p>
</div>
<div class="paragraph">
<p>This example was inspired by a popular GraphQL API.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="solution"><a class="anchor" href="#solution"></a>Solution</h2>
<div class="sectionbody">
<div class="paragraph">
<p>We recommend that you follow the instructions in the next sections and create the application step by step.
However, you can go right to the completed example.</p>
</div>
<div class="paragraph">
<p>Clone the Git repository: <code>git clone <a href="https://github.com/quarkusio/quarkus-quickstarts.git" class="bare">https://github.com/quarkusio/quarkus-quickstarts.git</a></code>, or download an <a href="https://github.com/quarkusio/quarkus-quickstarts/archive/master.zip">archive</a>.</p>
</div>
<div class="paragraph">
<p>The solution is located in the <code>microprofile-graphql-quickstart</code> <a href="https://github.com/quarkusio/quarkus-quickstarts/tree/master/microprofile-graphql-quickstart">directory</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="creating-the-maven-project"><a class="anchor" href="#creating-the-maven-project"></a>Creating the Maven Project</h2>
<div class="sectionbody">
<div class="paragraph">
<p>First, we need a new project. Create a new project with the following command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-none hljs">mvn io.quarkus:quarkus-maven-plugin:1.7.0.Final:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=microprofile-graphql-quickstart \
    -DclassName="org.acme.microprofile.graphql.FilmResource" \
    -Dextensions="graphql"
cd microprofile-graphql-quickstart</code></pre>
</div>
</div>
<div class="paragraph">
<p>This command generates a Maven project, importing the <code>smallrye-graphql</code> extension which is an implementation of the MicroProfile GraphQL specification used in Quarkus.</p>
</div>
<div class="paragraph">
<p>If you already have your Quarkus project configured, you can add the <code>smallrye-graphql</code> extension
to your project by running the following command in your project base directory:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="bash" class="language-bash hljs">./mvnw quarkus:add-extension -Dextensions="graphql"</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will add the following to your <code>pom.xml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="xml" class="language-xml hljs">&lt;dependency&gt;
    &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
    &lt;artifactId&gt;quarkus-smallrye-graphql&lt;/artifactId&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="preparing-an-application-graphql-api"><a class="anchor" href="#preparing-an-application-graphql-api"></a>Preparing an Application: GraphQL API</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In this section we will start creating the GraphQL API.</p>
</div>
<div class="paragraph">
<p>First, create the following entities representing a film from a galaxy far far away:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">package org.acme.microprofile.graphql;

public class Film {

    private String title;
    private Integer episodeID;
    private String director;
    private LocalDate releaseDate;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getEpisodeID() {
        return episodeID;
    }

    public void setEpisodeID(Integer episodeID) {
        this.episodeID = episodeID;
    }

    public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }

    public LocalDate getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(LocalDate releaseDate) {
        this.releaseDate = releaseDate;
    }

}

public class Hero {

    private String name;
    private String surname;
    private Double height;
    private Integer mass;
    private Boolean darkSide;
    private LightSaber lightSaber;
    private List&lt;Integer&gt; episodeIds = new ArrayList&lt;&gt;();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Double getHeight() {
        return height;
    }

    public void setHeight(Double height) {
        this.height = height;
    }

    public Integer getMass() {
        return mass;
    }

    public void setMass(Integer mass) {
        this.mass = mass;
    }

    public Boolean getDarkSide() {
        return darkSide;
    }

    public void setDarkSide(Boolean darkSide) {
        this.darkSide = darkSide;
    }

    public LightSaber getLightSaber() {
        return lightSaber;
    }

    public void setLightSaber(LightSaber lightSaber) {
        this.lightSaber = lightSaber;
    }

    public List&lt;Integer&gt; getEpisodeIds() {
        return episodeIds;
    }

    public void setEpisodeIds(List&lt;Integer&gt; episodeIds) {
        this.episodeIds = episodeIds;
    }
}

enum LightSaber {
    RED, BLUE, GREEN
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The classes we have just created describe the GraphQL schema which is a
set of possible data (objects, fields, relationships) that a client can access.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s continue with an example CDI bean, that would work as a repository:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@ApplicationScoped
public class GalaxyService {

    private List&lt;Hero&gt; heroes = new ArrayList&lt;&gt;();

    private List&lt;Film&gt; films = new ArrayList&lt;&gt;();

    public GalaxyService() {

        Film aNewHope = new Film();
        aNewHope.setTitle("A New Hope");
        aNewHope.setReleaseDate(LocalDate.of(1977, Month.MAY, 25));
        aNewHope.setEpisodeID(4);
        aNewHope.setDirector("George Lucas");

        Film theEmpireStrikesBack = new Film();
        theEmpireStrikesBack.setTitle("The Empire Strikes Back");
        theEmpireStrikesBack.setReleaseDate(LocalDate.of(1980, Month.MAY, 21));
        theEmpireStrikesBack.setEpisodeID(5);
        theEmpireStrikesBack.setDirector("George Lucas");

        Film returnOfTheJedi = new Film();
        returnOfTheJedi.setTitle("Return Of The Jedi");
        returnOfTheJedi.setReleaseDate(LocalDate.of(1983, Month.MAY, 25));
        returnOfTheJedi.setEpisodeID(6);
        returnOfTheJedi.setDirector("George Lucas");

        films.add(aNewHope);
        films.add(theEmpireStrikesBack);
        films.add(returnOfTheJedi);

        Hero luke = new Hero();
        luke.setName("Luke");
        luke.setSurname("Skywalker");
        luke.setHeight(1.7);
        luke.setMass(73);
        luke.setLightSaber(LightSaber.GREEN);
        luke.setDarkSide(false);
        luke.getEpisodeIds().addAll(Arrays.asList(4, 5, 6));

        Hero leia = new Hero();
        leia.setName("Leia");
        leia.setSurname("Organa");
        leia.setHeight(1.5);
        leia.setMass(51);
        leia.setDarkSide(false);
        leia.getEpisodeIds().addAll(Arrays.asList(4, 5, 6));


        Hero vader = new Hero();
        vader.setName("Darth");
        vader.setSurname("Vader");
        vader.setHeight(1.9);
        vader.setMass(89);
        vader.setDarkSide(true);
        vader.setLightSaber(LightSaber.RED);
        vader.getEpisodeIds().addAll(Arrays.asList(4, 5, 6));

        heroes.add(luke);
        heroes.add(leia);
        heroes.add(vader);

    }

    public List&lt;Film&gt; getAllFilms() {
        return films;
    }

    public Film getFilm(int id) {
        return films.get(id);
    }

    public List&lt;Hero&gt; getHeroesByFilm(Film film) {
        return heroes.stream()
                .filter(hero -&gt; hero.getEpisodeIds().contains(film.getEpisodeID()))
                .collect(Collectors.toList());
    }

    public void addHero(Hero hero) {
        heroes.add(hero);
    }

    public Hero deleteHero(int id) {
        return heroes.remove(id);
    }

    public List&lt;Hero&gt; getHeroesBySurname(String surname) {
        return heroes.stream()
                .filter(hero -&gt; hero.getSurname().equals(surname))
                .collect(Collectors.toList());
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now, let&#8217;s create our first GraphQL API.</p>
</div>
<div class="paragraph">
<p>Edit the <code>org.acme.microprofile.graphql.FilmResource</code> class as following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@GraphQLApi <i class="conum" data-value="1"></i><b>(1)</b>
public class FilmResource {

    @Inject
    GalaxyService service;

    @Query("allFilms") <i class="conum" data-value="2"></i><b>(2)</b>
    @Description("Get all Films from a galaxy far far away") <i class="conum" data-value="3"></i><b>(3)</b>
    public List&lt;Film&gt; getAllFilms() {
        return service.getAllFilms();
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td><code>@GraphQLApi</code> annotation indicates that the CDI bean will be a GraphQL endpoint</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td><code>@Query</code> annotation defines that this method will be queryable with the name <code>allFilms</code></td>
</tr>
<tr>
<td><i class="conum" data-value="3"></i><b>3</b></td>
<td>Documentation of the queryable method</td>
</tr>
</table>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
The value of the <code>@Query</code> annotation is optional and would implicitly
be defaulted to the method name if absent.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>This way we have created our first queryable API which we will later expand.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="launch"><a class="anchor" href="#launch"></a>Launch</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Launch the quarkus app:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="bash" class="language-bash hljs">./mvnw compile quarkus:dev</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="introspect"><a class="anchor" href="#introspect"></a>Introspect</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The full schema of the GraphQL API can be retrieved by calling the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-none hljs">curl http://localhost:8080/graphql/schema.graphql</code></pre>
</div>
</div>
<div class="paragraph">
<p>The server will return the complete schema of the GraphQL API.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="graphiql-ui"><a class="anchor" href="#graphiql-ui"></a>GraphiQL UI</h2>
<div class="sectionbody">
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Experimental - not included in the MicroProfile specification
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>GraphiQL UI is a great tool permitting easy interaction with your GraphQL APIs.</p>
</div>
<div class="paragraph">
<p>The Quarkus <code>smallrye-graphql</code> extension ships with <code>GraphiQL</code> and enables it by default in <code>dev</code> and <code>test</code> modes,
but it can also be explicitly configured for <code>production</code> mode as well.</p>
</div>
<div class="paragraph">
<p>GraphiQL can be accessed from <a href="http://localhost:8080/graphql-ui/" class="bare">http://localhost:8080/graphql-ui/</a> .</p>
</div>
<div class="paragraph">
<p><span class="image"><img src="/guides/images/graphql-ui-screenshot01.png" alt="GraphQL UI"></span></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="query-the-graphql-api"><a class="anchor" href="#query-the-graphql-api"></a>Query the GraphQL API</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Now visit the GraphiQL page that has been deployed in <code>dev</code> mode.</p>
</div>
<div class="paragraph">
<p>Enter the following query to GraphiQL and press the <code>play</code> button:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">query allFilms {
  allFilms {
    title
    director
    releaseDate
    episodeID
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Since our query contains all the fields in the <code>Film</code> class
we will retrieve all the fields in our response. Since GraphQL API
responses are client determined, the client can choose which fields
it will require.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s assume that our client only requires <code>title</code> and <code>releaseDate</code>
making the previous call to the API <code>Over-fetching</code> of unnecessary
data.</p>
</div>
<div class="paragraph">
<p>Enter the following query into GraphiQL and hit the <code>play</code> button:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">query allFilms {
  allFilms {
    title
    releaseDate
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice in the response we have only retrieved the required fields.
Therefore, we have prevented <code>Over-fetching</code>.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s continue to expand our GraphQL API by adding the following to the
<code>FilmResource</code> class.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">    @Query
    @Description("Get a Films from a galaxy far far away")
    public Film getFilm(@Name("filmId") int id) {
        return service.getFilm(id);
    }</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Notice how we have excluded the value in the <code>@Query</code> annotation.
Therefore, the name of the query is implicitly set as the method name
excluding the <code>get</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>This query will allow the client to retrieve the film by id.</p>
</div>
<div class="paragraph">
<p>Enter the following into <code>GraphiQL</code> and make a request.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">query getFilm {
  film(filmId: 1) {
    title
    director
    releaseDate
    episodeID
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>film</code> query method requested fields can be determined
as such in our previous example. This way we can retrieve individual
film information.</p>
</div>
<div class="paragraph">
<p>However, say our client requires both films with filmId <code>0</code> and <code>1</code>.
In a REST API the client would have to make two calls to the API.
Therefore, the client would be <code>Under-fetching</code>.</p>
</div>
<div class="paragraph">
<p>In GraphQL it is possible to make multiple queries at once.</p>
</div>
<div class="paragraph">
<p>Enter the following into GraphiQL to retrieve two films:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">query getFilms {
  film0: film(filmId: 0) {
    title
    director
    releaseDate
    episodeID
  }
  film1: film(filmId: 1) {
    title
    director
    releaseDate
    episodeID
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This enabled the client to fetch the required data in a single request.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="expanding-the-api"><a class="anchor" href="#expanding-the-api"></a>Expanding the API</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Until now, we have created a GraphQL API to retrieve film data.
We now want to enable the clients to retrieve the <code>Hero</code> data of the <code>Film</code>.</p>
</div>
<div class="paragraph">
<p>Add the following to our <code>FilmResource</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">    public List&lt;Hero&gt; heroes(@Source Film film) { <i class="conum" data-value="1"></i><b>(1)</b>
        return service.getHeroesByFilm(film);
    }</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>Enable <code>List&lt;Hero&gt;</code> data to be added to queries that respond with <code>Film</code></td>
</tr>
</table>
</div>
<div class="paragraph">
<p>By adding this method we have effectively changed the schema of the GraphQL API.
Although the schema has changed the previous queries will still work.
Since we only expanded the API to be able to retrieve the <code>Hero</code> data of the <code>Film</code>.</p>
</div>
<div class="paragraph">
<p>Enter the following into GraphiQL to retrieve the film and hero data.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">query getFilmHeroes {
  film(filmId: 1) {
    title
    director
    releaseDate
    episodeID
    heroes {
      name
      height
      mass
      darkSide
      lightSaber
    }
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The response now includes the heroes of the film.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="mutations"><a class="anchor" href="#mutations"></a>Mutations</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Mutations are used when data is created, updated or deleted.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s now add the ability to add and delete heroes to our GraphQL API.</p>
</div>
<div class="paragraph">
<p>Add the following to our <code>FilmResource</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">    @Mutation
    public Hero createHero(Hero hero) {
        service.addHero(hero);
        return hero;
    }

    @Mutation
    public Hero deleteHero(int id) {
        return service.deleteHero(id);
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Enter the following into <code>GraphiQL</code> to insert a <code>Hero</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">mutation addHero {
  createHero(hero: {
      name: "Han",
      surname: "Solo"
      height: 1.85
      mass: 80
      darkSide: false
      episodeIds: [4, 5, 6]
  	}
  )
  {
    name
    surname
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By using this mutation we have created a <code>Hero</code> entity in our service.</p>
</div>
<div class="paragraph">
<p>Notice how in the response we have retrieved the <code>name</code> and <code>surname</code>
of the created Hero. This is because we selected to retrieve
these fields in the response within the <code>{ }</code> in the mutation query.
This can easily be a server side generated field that the client may require.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s now try deleting an entry:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>mutation DeleteHero {
  deleteHero(id :3){
    name
    surname
  }
}</pre>
</div>
</div>
<div class="paragraph">
<p>Similar to the <code>createHero</code> mutation method we also retrieve the <code>name</code> and
<code>surname</code> of the hero we have deleted which is defined in <code>{ }</code>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="creating-queries-by-fields"><a class="anchor" href="#creating-queries-by-fields"></a>Creating Queries by fields</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Queries can also be done on individual fields. For example, let&#8217;s
create a method to query heroes by their last name.</p>
</div>
<div class="paragraph">
<p>Add the following to our <code>FilmResource</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">    @Query
    public List&lt;Hero&gt; getHeroesWithSurname(@DefaultValue("Skywalker") String surname) {
        return service.getHeroesBySurname(surname);
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>By using the <code>@DefaultValue</code> annotation we have determined that the surname value
will be <code>Skywalker</code> when the parameter is not provided.</p>
</div>
<div class="paragraph">
<p>Test the following queries with GraphiQL:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">query heroWithDefaultSurname {
  heroesWithSurname{
    name
    surname
    lightSaber
  }
}
query heroWithSurnames {
  heroesWithSurname(surname: "Vader") {
    name
    surname
    lightSaber
  }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="context"><a class="anchor" href="#context"></a>Context</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can get information about the GraphQL request anywhere in your code, using this experimental, SmallRye specific feature:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@Inject
Context context;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The context object allows you to get:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>the original request (Query/Mutation)</p>
</li>
<li>
<p>the arguments</p>
</li>
<li>
<p>the path</p>
</li>
<li>
<p>the selected fields</p>
</li>
<li>
<p>any variables</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>This allows you to optimize the downstream queries to the datastore.</p>
</div>
<div class="paragraph">
<p>See the <a href="https://javadoc.io/doc/io.smallrye/smallrye-graphql-api/latest/io/smallrye/graphql/api/Context.html">JavaDoc</a> for more details.</p>
</div>
<div class="sect2">
<h3 id="graphql-java"><a class="anchor" href="#graphql-java"></a>GraphQL-Java</h3>
<div class="paragraph">
<p>This context object also allows you to fall down to the underlying <a href="https://www.graphql-java.com/">graphql-java</a> features by using the leaky abstraction:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">DataFetchingEnvironment dfe = context.unwrap(DataFetchingEnvironment.class);</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also get access to the underlying <code>graphql-java</code> during schema generation, to add your own features directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">public GraphQLSchema.Builder addMyOwnEnum(@Observes GraphQLSchema.Builder builder) {

    // Here add your own features directly, example adding an Enum
    GraphQLEnumType myOwnEnum = GraphQLEnumType.newEnum()
            .name("SomeEnum")
            .description("Adding some enum type")
            .value("value1")
            .value("value2").build();

    return builder.additionalType(myOwnEnum);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By using the <code>@Observer</code> you can add anything to the Schema builder.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="map-to-scalar"><a class="anchor" href="#map-to-scalar"></a>Map to Scalar</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Another SmallRye specific experimental feature, allows you to map an existing scalar (that is mapped by the implementation to a certain Java type) to another type,
or to map complex object, that would typically create a <code>Type</code> or <code>Input</code> in GraphQL, to an existing scalar.</p>
</div>
<div class="sect2">
<h3 id="mapping-an-existing-scalar-to-another-type"><a class="anchor" href="#mapping-an-existing-scalar-to-another-type"></a>Mapping an existing Scalar to another type:</h3>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">public class Movie {

    @ToScalar(Scalar.Int.class)
    Long idLongThatShouldChangeToInt;

    // ....
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Above will map the <code>Long</code> java type to an <code>Int</code> Scalar type, rather than the <a href="https://download.eclipse.org/microprofile/microprofile-graphql-1.0/microprofile-graphql.html#scalars">default</a> <code>BigInteger</code>.</p>
</div>
</div>
<div class="sect2">
<h3 id="mapping-a-complex-object-to-a-scalar-type"><a class="anchor" href="#mapping-a-complex-object-to-a-scalar-type"></a>Mapping a complex object to a Scalar type:</h3>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">public class Person {

    @ToScalar(Scalar.String.class)
    Phone phone;

    // ....
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will, rather than creating a <code>Type</code> or <code>Input</code> in GraphQL, map to a String scalar.</p>
</div>
<div class="paragraph">
<p>To be able to do the above, the <code>Phone</code> object needs to have a constructor that takes a String (or <code>Int</code> / <code>Date</code> / etc.),
or have a setter method for the String  (or <code>Int</code> / <code>Date</code> / etc.),
or have a <code>fromString</code> (or <code>fromInt</code> / <code>fromDate</code> - depending on the Scalar type) static method.</p>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">public class Phone {

    private String number;

    // Getters and setters....

    public static Phone fromString(String number) {
        Phone phone = new Phone();
        phone.setNumber(number);
        return phone;
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>See more about the <code>@ToScalar</code> feature in the <a href="https://javadoc.io/static/io.smallrye/smallrye-graphql-api/1.0.6/index.html?io/smallrye/graphql/api/ToScalar.html">JavaDoc</a>.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="error-code"><a class="anchor" href="#error-code"></a>Error code</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can add an error code on the error output in the GraphQL response by using the (SmallRye specific) <code>@ErrorCode</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@ErrorCode("some-business-error-code")
public class SomeBusinessException extends RuntimeException {
    // ...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When <code>SomeBusinessException</code> occurs, the error output will contain the Error code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="graphql" class="language-graphql hljs">{
    "errors": [
        {
            "message": "Unexpected failure in the system. Jarvis is working to fix it.",
            "locations": [
                {
                    "line": 2,
                    "column": 3
                }
            ],
            "path": [
                "annotatedCustomBusinessException"
            ],
            "extensions": {
                "exception": "io.smallrye.graphql.test.apps.error.api.ErrorApi$AnnotatedCustomBusinessException",
                "classification": "DataFetchingException",
                "code": "some-business-error-code" <i class="conum" data-value="1"></i><b>(1)</b>
            }
        }
    ],
    "data": {
        ...
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>The error code</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="conclusion"><a class="anchor" href="#conclusion"></a>Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p>MicroProfile GraphQL enables clients to retrieve the exact data that is
required preventing <code>Over-fetching</code> and <code>Under-fetching</code>.</p>
</div>
<div class="paragraph">
<p>The GraphQL API can be expanded without breaking previous queries enabling easy
API <code>evolution</code>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="configuration-reference"><a class="anchor" href="#configuration-reference"></a>Configuration Reference</h2>
<div class="sectionbody">
<div class="paragraph configuration-legend">
<p><span class="icon"><i class="fa fa-lock" title="Fixed at build time"></i></span> Configuration property fixed at build time - All other configuration properties are overridable at runtime</p>
</div>
<table class="tableblock frame-all grid-all stretch configuration-reference searchable">
<colgroup>
<col style="width: 80%;">
<col style="width: 10%;">
<col style="width: 10%;">
</colgroup>
<tbody>
<tr>
<th class="tableblock halign-left valign-top"><p class="tableblock"><a id="quarkus-smallrye-graphql_configuration"></a><a href="#quarkus-smallrye-graphql_configuration">Configuration property</a></p></th>
<th class="tableblock halign-left valign-middle"><p class="tableblock">Type</p></th>
<th class="tableblock halign-left valign-middle"><p class="tableblock">Default</p></th>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><div class="content"><div class="paragraph">
<p><span class="icon"><i class="fa fa-lock" title="Fixed at build time"></i></span> <a id="quarkus-smallrye-graphql_quarkus.smallrye-graphql.root-path"></a><code><a href="#quarkus-smallrye-graphql_quarkus.smallrye-graphql.root-path">quarkus.smallrye-graphql.root-path</a></code></p>
</div>
<div class="openblock description">
<div class="content">
<div class="paragraph">
<p>The rootPath under which queries will be served. Default to /graphql</p>
</div>
</div>
</div></div></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock">string</p></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock"><code>/graphql</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><div class="content"><div class="paragraph">
<p><span class="icon"><i class="fa fa-lock" title="Fixed at build time"></i></span> <a id="quarkus-smallrye-graphql_quarkus.smallrye-graphql.metrics.enabled"></a><code><a href="#quarkus-smallrye-graphql_quarkus.smallrye-graphql.metrics.enabled">quarkus.smallrye-graphql.metrics.enabled</a></code></p>
</div>
<div class="openblock description">
<div class="content">
<div class="paragraph">
<p>Enable metrics</p>
</div>
</div>
</div></div></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock">boolean</p></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock"><code>false</code></p></td>
</tr>
<tr>
<th class="tableblock halign-left valign-top"><p class="tableblock"><a id="quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui"></a><a href="#quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui">UI configuration</a></p></th>
<th class="tableblock halign-left valign-middle"><p class="tableblock">Type</p></th>
<th class="tableblock halign-left valign-middle"><p class="tableblock">Default</p></th>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><div class="content"><div class="paragraph">
<p><span class="icon"><i class="fa fa-lock" title="Fixed at build time"></i></span> <a id="quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui.root-path"></a><code><a href="#quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui.root-path">quarkus.smallrye-graphql.ui.root-path</a></code></p>
</div>
<div class="openblock description">
<div class="content">
<div class="paragraph">
<p>The path where GraphQL UI is available. The value <code>/</code> is not allowed as it blocks the application from serving anything else.</p>
</div>
</div>
</div></div></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock">string</p></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock"><code>/graphql-ui</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><div class="content"><div class="paragraph">
<p><span class="icon"><i class="fa fa-lock" title="Fixed at build time"></i></span> <a id="quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui.always-include"></a><code><a href="#quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui.always-include">quarkus.smallrye-graphql.ui.always-include</a></code></p>
</div>
<div class="openblock description">
<div class="content">
<div class="paragraph">
<p>Always include the UI. By default this will only be included in dev and test. Setting this to true will also include the UI in Prod</p>
</div>
</div>
</div></div></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock">boolean</p></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock"><code>false</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><div class="content"><div class="paragraph">
<p><span class="icon"><i class="fa fa-lock" title="Fixed at build time"></i></span> <a id="quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui.enable"></a><code><a href="#quarkus-smallrye-graphql_quarkus.smallrye-graphql.ui.enable">quarkus.smallrye-graphql.ui.enable</a></code></p>
</div>
<div class="openblock description">
<div class="content">
<div class="paragraph">
<p>If GraphQL UI should be enabled. By default, GraphQL UI is enabled.</p>
</div>
</div>
</div></div></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock">boolean</p></td>
<td class="tableblock halign-left valign-middle"><p class="tableblock"><code>true</code></p></td>
</tr>
</tbody>
</table>
</div>
</div>
    </div>
  </div>
</div>

  </div>

  <div class="content project-footer">
  <div class="footer-section">
    <div class="logo-wrapper">
      <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_reverse.svg" class="project-logo" title="Quarkus"></a>
    </div>
  </div>
  <div class="grid-wrapper">
    <p class="grid__item width-3-12">Quarkus is open. All dependencies of this project are available under the <a href='https://www.apache.org/licenses/LICENSE-2.0' target='_blank'>Apache Software License 2.0</a> or compatible license.<br /><br />This website was built with <a href='https://jekyllrb.com/' target='_blank'>Jekyll</a>, is hosted on <a href='https://pages.github.com/' target='_blank'>Github Pages</a> and is completely open source. If you want to make it better, <a href='https://github.com/quarkusio/quarkusio.github.io' target='_blank'>fork the website</a> and show us what you’ve got.</p>

    
      <div class="width-1-12 project-links">
        <span>Navigation</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="/">Home</a></li>
          
            <li><a href="/guides">Guides</a></li>
          
            <li><a href="/community/#contributing">Contribute</a></li>
          
            <li><a href="/faq">FAQ</a></li>
          
            <li><a href="/get-started">Get Started</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Contribute</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://twitter.com/quarkusio">Follow us</a></li>
          
            <li><a href="https://github.com/quarkusio">GitHub</a></li>
          
            <li><a href="/security">Security&nbsp;policy</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Get Help</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://groups.google.com/forum/#!forum/quarkus-dev">Forums</a></li>
          
            <li><a href="https://quarkusio.zulipchat.com">Chatroom</a></li>
          
        </ul>
      </div>
    

    
      <div class="width-3-12 more-links">
        <span>Quarkus is made of community projects</span>
        <ul class="footer-links">
          
            <li><a href="https://vertx.io/" target="_blank">Eclipse Vert.x</a></li>
          
            <li><a href="https://microprofile.io" target="_blank">Eclipse MicroProfile</a></li>
          
            <li><a href="https://hibernate.org" target="_blank">Hibernate</a></li>
          
            <li><a href="https://netty.io" target="_blank">Netty</a></li>
          
            <li><a href="https://resteasy.github.io" target="_blank">RESTEasy</a></li>
          
            <li><a href="https://camel.apache.org" target="_blank">Apache Camel</a></li>
          
            <li><a href="https://code.quarkus.io/" target="_blank">And many more...</a></li>
          
        </ul>
      </div>
    
  </div>
</div>
  <div class="content redhat-footer">
  <div class="grid-wrapper">
    <span class="licence">
      <i class="fab fa-creative-commons"></i><i class="fab fa-creative-commons-by"></i> <a href="https://creativecommons.org/licenses/by/3.0/" target="_blank">CC by 3.0</a> | <a href="https://www.redhat.com/en/about/privacy-policy">Privacy Policy</a>
    </span>
    <span class="redhat">
      Sponsored by
    </span>
    <span class="redhat-logo">
      <a href="https://www.redhat.com/" target="_blank"><img src="/assets/images/redhat_reversed.svg"></a>
    </span>
  </div>
</div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" integrity="sha384-8gBf6Y4YYq7Jx97PIqmTwLPin4hxIzQw5aDmUg/DDhul9fFpbbLcLh3nTIIDJKhx" crossorigin="anonymous"></script>
  <script type="text/javascript" src="/assets/javascript/mobile-nav.js"></script>
  <script type="text/javascript" src="/assets/javascript/scroll-down.js"></script>
  <script src="/assets/javascript/satellite.js" type="text/javascript"></script>
  <script src="https://quarkus.io/guides/javascript/config.js" type="text/javascript"></script>
  <script src="/assets/javascript/search-filter.js" type="text/javascript"></script>
  <script src="/assets/javascript/back-to-top.js" type="text/javascript"></script>
</body>

</html>
